package com.yuyu.qingmangmall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysql.cj.util.StringUtils;
import com.yuyu.common.constant.ProductConstant;
import com.yuyu.common.to.SkuHasStockVo;
import com.yuyu.common.to.SkuReductionTo;
import com.yuyu.common.to.SpuBoundTo;
import com.yuyu.common.to.es.SkuEsModel;
import com.yuyu.common.utils.PageUtils;
import com.yuyu.common.utils.Query;
import com.yuyu.common.utils.R;
import com.yuyu.qingmangmall.product.dao.SpuInfoDao;
import com.yuyu.qingmangmall.product.entity.*;
import com.yuyu.qingmangmall.product.feign.CouponFeignService;
import com.yuyu.qingmangmall.product.feign.SearchFeignService;
import com.yuyu.qingmangmall.product.feign.WareFeignService;
import com.yuyu.qingmangmall.product.service.*;
import com.yuyu.qingmangmall.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SpuImagesService spuImagesService;

    @Autowired
    AttrService attrService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    BrandService brandService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * TODO 高级部分在完善
     * @param spuInfo
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuInfo) {

        // 1.保存Spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date()); //
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);
//        this.baseMapper.insert()

        // 2.保存Spu的描述图片 pms_spu_info_desc (desc:描述)
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        List<String> decript = spuInfo.getDecript();
        String join = String.join(",", decript);
        spuInfoDescEntity.setDecript(join);

        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);

        // 3.保存spu的图片集  pms_spu_images
        List<String> images = spuInfo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(),images);

        // 4.保存spu的规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuInfo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(baseAttr -> {
            ProductAttrValueEntity attrValue = new ProductAttrValueEntity();
            attrValue.setAttrId(baseAttr.getAttrId());

            AttrEntity id = attrService.getById(baseAttr.getAttrId());
            attrValue.setAttrName(id.getAttrName());
            attrValue.setAttrValue(baseAttr.getAttrValues());
            attrValue.setQuickShow(baseAttr.getShowDesc());
            attrValue.setSpuId(spuInfoEntity.getId());
            return attrValue;
        }).collect(Collectors.toList());

        productAttrValueService.saveProductAttr(collect);

        // 5.保存spu的积分信息  qingmangmall_sms -> sms_spu_bounds (bounds:范围)
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        Bounds bounds = spuInfo.getBounds();
        BeanUtils.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTo);

        if (r.getCode() != 0){
            log.error("远程保存spu积分信息失败");
        }

        // 5.保存当前spu对应的sku信息


        List<Skus> skus = spuInfo.getSkus();

        if (skus != null && skus.size()>0) {
            skus.forEach(item->{
                String defaultImg = "";

                for (Images images1 : item.getImages()) {
                    if (images1.getDefaultImg()==1){
                        defaultImg = images1.getImgUrl();
                    }
                }
                //        private String skuName; sku名称
        //        private BigDecimal price; 价格
        //        private String skuTitle; 标题
        //        private String skuSubtitle; 副标题

                // 5.1 sku的基本信息  pms_sku_info
                SkuInfoEntity skuInfoEntityA = new SkuInfoEntity();
                BeanUtils.copyProperties(item,skuInfoEntityA);

                skuInfoEntityA.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntityA.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntityA.setSaleCount(0L);
                skuInfoEntityA.setSpuId(spuInfoEntity.getId());
                skuInfoEntityA.setSkuDefaultImg(defaultImg);

                // 5.1 sku的基本信息  pms_sku_info
                skuInfoService.saveSkuInfo(skuInfoEntityA);

                Long skuId = skuInfoEntityA.getSkuId();

                List<SkuImagesEntity> imagesEntities = item.getImages().stream().filter(image->
                {
                    // 拿到 图片路径不为空的 Images
//                   return  !image.getImgUrl().isEmpty();
                   return !StringUtils.isNullOrEmpty(image.getImgUrl());
                }).map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();

                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    return skuImagesEntity;
                }).collect(Collectors.toList());

                // 5.2 sku的图片信息  pms_sku_images
                // TODO 没有图片路径的 无需保存
                skuImagesService.saveBatch(imagesEntities);


                List<Attr> attrList = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrList.stream().map(attr -> {
                    SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, attrValueEntity);
                    attrValueEntity.setSkuId(skuId);

                    return attrValueEntity;
                }).collect(Collectors.toList());
                // 5.3 sku的销售属性信息  pms_sku_sale_attr_value
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                //      (ladder:范围, full:完整的, reduction:减少, member:会员, price:价格)
                // 5.4 sku的优惠、满减等信息  qingmangmall_sms -> sms_sku_ladder\sms_sku_full_reduction\sms_member_price
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item,skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullPrice().compareTo(new BigDecimal("0"))==1 || skuReductionTo.getDiscount().compareTo(new BigDecimal("0"))==1) {
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r1.getCode() != 0){
                        log.error("远程保存sku的优惠、满减等信息失败");
                    }
                }


            });

        }







    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
//        this.save()
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {

        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        /*
        key: 1
        status: 0
        brandId: 5
        catelogId: 225
         */
        String key = (String) params.get("key");
        if (!StringUtils.isNullOrEmpty(key)) {
            wrapper.and(wrap->{
                wrap.eq("id",key).or().like("spu_name",key);
            });
        }

        String status = (String) params.get("status");
        if (!StringUtils.isNullOrEmpty(status) && !"0".equalsIgnoreCase(status)) {
            wrapper.eq("publish_status",status);
        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isNullOrEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            wrapper.eq("brand_id",brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isNullOrEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            wrapper.eq("catalog_id",catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params),
                wrapper);


        return new PageUtils(page);

    }

    /**
     * 商品上架
     * @param spuId
     */
    @Override
    public void spuUp(Long spuId) {
        // 1.查出当前spuId对应的所有sku信息,品牌名字
        List<SkuInfoEntity> skus = skuInfoService.getSkuBySpuId(spuId);

        // TODO 4. 查询当前sku的所有可以被用来检索的规格属性
        List<ProductAttrValueEntity> productAttrValues = productAttrValueService.getAttrBySpuId(spuId);
        List<Long> attrIds = productAttrValues.stream().map(productAttr -> {
            return productAttr.getAttrId();
        }).collect(Collectors.toList());

        // 拿到attrs
        List<Long> searchAttrIds = attrService.getSearchAttrIds(attrIds);
        Set<Long> ids = new HashSet<>(searchAttrIds);
        List<SkuEsModel.Attr> skuAttrs = productAttrValues.stream().filter(attrs -> {
            return ids.contains(attrs.getAttrId());
        }).map(attr -> {
            SkuEsModel.Attr skuAttr = new SkuEsModel.Attr();
            BeanUtils.copyProperties(attr, skuAttr);
            return skuAttr;
        }).collect(Collectors.toList());

        //TODO 1. 发送远程调用，库存系统查询是否有库存
        List<Long> skuIds = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        Map<Long, Boolean> stockVos = null;
        try {
            R r = wareFeignService.getSkusHasStock(skuIds);
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {
            };
            List<SkuHasStockVo> skuHasStockVos = r.getData(typeReference);
            stockVos = skuHasStockVos.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));

        }catch (Exception e){
            log.error("远程调用，库存系统异常：{}",e);
        }

        // 组装需要的数据
        Map<Long, Boolean> finalStockVos = stockVos;
        List<SkuEsModel> upProducts = skus.stream().map(skuInfo -> {
            // 组装每个sku的信息
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(skuInfo, skuEsModel);

            // skuPrice, skuImg
            skuEsModel.setSkuPrice(skuInfo.getPrice());
            skuEsModel.setSkuImg(skuInfo.getSkuDefaultImg());
            // hasStock, hotScore
            // 设置库存信息
            if (finalStockVos==null){
                // 如果远程调用库存服务出现问题，默认有库存
                skuEsModel.setHasStock(true);
            }else {
                skuEsModel.setHasStock(finalStockVos.get(skuInfo.getSkuId()));
            }
            //TODO 2. 热度评分。先写成0
            skuEsModel.setHotScore(0L);

            //TODO 3. 查询品牌和分类的名字信息

            /**
             *     private String brandName;
             *     private String brandImg;
             *     private String catalogName;
             */
            BrandEntity brandEntity = brandService.getById(skuInfo.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());

            CategoryEntity categoryEntity = categoryService.getById(skuInfo.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());
            // 设置检索属性
            skuEsModel.setAttrs(skuAttrs);


            return skuEsModel;
        }).collect(Collectors.toList());

            // TODO 5. 将数据发送给es进行保存  qingmangmall-search
        R r = searchFeignService.productStatusUp(upProducts);
        if (r.getCode()==0){
            // 远程调用成功
            // TODO 6. 修改当前spu的状态
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        } else {
            // 远程调用失败
            // TODO 7.重复调用？ 接口幂等性；重试机制？xxx
            // Feign调用流程
            /**
             * 1. 构造请求数据，将对象转为json
             *      RequestTemplate template = this.buildTemplateFromArgs.create(argv);
             * 2. 发送请求进行执行（执行成功会解码响应数据）
             *      executeAndDecode(template, options);
             * 3. 执行请求会有重试机制
             *       where(true){
             *       try {
             *             return this.executeAndDecode(template, options);
             *         } catch () {
             *                 try{
             *                 retryer.continueOrPropagate(e);
             *                 }catch(){
             *                     throw e;
             *                 }
             *                 continue;
             *          }
             *      }
             */

        }
    }

    @Override
    public SpuInfoEntity getSpuBySkuId(Long skuId) {
        SkuInfoEntity skuInfoEntity = skuInfoService.getById(skuId);
        Long spuId = skuInfoEntity.getSpuId();
        return this.getById(spuId);
    }

}